package com.zx.freeapi.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zx.freeapi.exception.BusinessException;
import com.zx.freeapi.model.entity.User;
import com.zx.freeapi.model.enums.ErrorCode;
import com.zx.freeapi.model.vo.UserVO;
import com.zx.freeapi.service.UserService;
import com.zx.freeapi.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.zx.freeapi.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author darling
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-03-15 21:34:12
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Override
    public String encryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = "darling";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        User userObj = (User)request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj.getId() == null || userObj == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = userObj.getId();
        userObj = this.getById(userId);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return userObj;



    }
    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        List<UserVO> userVOList = userList.stream().map(this::getUserVO).collect(Collectors.toList());
        return userVOList;
    }
}




